const Banner = require("../models/banner");

class BannerController {
  // 获取所有轮播图
  static async getAllBanners(req, res) {
    try {
      const banners = await Banner.getAll();
      res.json({ success: true, data: banners });
    } catch (error) {
      console.error("Error getting banners:", error);
      res.status(500).json({ success: false, message: "获取轮播图列表失败" });
    }
  }

  // 获取单个轮播图
  static async getBannerById(req, res) {
    try {
      const { id } = req.params;
      const banner = await Banner.getById(id);
      if (!banner) {
        return res
          .status(404)
          .json({ success: false, message: "轮播图不存在" });
      }
      res.json({ success: true, data: banner });
    } catch (error) {
      console.error("Error getting banner:", error);
      res.status(500).json({ success: false, message: "获取轮播图详情失败" });
    }
  }

  // 创建轮播图
  static async createBanner(req, res) {
    try {
      const bannerData = req.body;
      if (!bannerData.image_url) {
        return res
          .status(400)
          .json({ success: false, message: "图片URL不能为空" });
      }
      const bannerId = await Banner.create(bannerData);
      res.status(201).json({ success: true, data: { id: bannerId } });
    } catch (error) {
      console.error("Error creating banner:", error);
      res.status(500).json({ success: false, message: "创建轮播图失败" });
    }
  }

  // 更新轮播图
  static async updateBanner(req, res) {
    try {
      const { id } = req.params;
      const bannerData = req.body;
      const success = await Banner.update(id, bannerData);
      if (!success) {
        return res
          .status(404)
          .json({ success: false, message: "轮播图不存在" });
      }
      res.json({ success: true, message: "更新成功" });
    } catch (error) {
      console.error("Error updating banner:", error);
      res.status(500).json({ success: false, message: "更新轮播图失败" });
    }
  }

  // 删除轮播图
  static async deleteBanner(req, res) {
    try {
      const { id } = req.params;
      const success = await Banner.delete(id);
      if (!success) {
        return res
          .status(404)
          .json({ success: false, message: "轮播图不存在" });
      }
      res.json({ success: true, message: "删除成功" });
    } catch (error) {
      console.error("Error deleting banner:", error);
      res.status(500).json({ success: false, message: "删除轮播图失败" });
    }
  }
}

module.exports = BannerController;
